<?php

namespace app\common\library;

use app\common\exception\UploadException;
use app\admin\model\SubjectAttachment;
use think\Exception;
use fast\Random;
use FilesystemIterator;
use think\Config;
use think\File;
use think\Hook;
use think\Log;

/**
 * 用户服务类
 */
class User
{
    /**
     * 获取9代单传上级
     */
    public static function getParentRelations($uid, $father, $now_gen = 1, $total_gen = 10, &$users_array) {
        
        if ($now_gen >= $total_gen) {
//            echo '找到顶级'.$now_gen.PHP_EOL;
            return $users_array;
        }
        $user = \think\Db::name("expert_relation er")->join("user u", "er.user_id=u.id", "LEFT")->where("er.user_id", $uid)->field("u.*,er.up_user_id,er.status as r_status")->find();
        // exit(print_r($user));
//        echo 'user_id=' .$user["mobile"]. '上一代 up_user_id=' .$user["up_user_id"].PHP_EOL;
        if ($user) {
//             echo 'user_id=' .$uid. '上一代 up_user_id=' .$user["up_user_id"].' mobile = '.$user["mobile"].PHP_EOL;
             //直推跳过
            if($uid == $father || $user["r_status"] == '0'){  //状态是:隐藏，跳到下一级  开启替换一下判断
//            if($uid == $father){ 
//                 echo '直推跳过'.$uid.'p='.$father.PHP_EOL;
                 return  self::getParentRelations($user["up_user_id"],$father, $now_gen, $total_gen, $users_array);
            }else{
                $now_gen++;
                $users_array[]=$user;
                return  self::getParentRelations($user["up_user_id"],$father, $now_gen, $total_gen, $users_array);
            }

            
            //状态是:隐藏，跳到下一级
//            if ($user["r_status"] == 0) {
//                  echo '隐藏' . PHP_EOL;
//                if ($now_gen > $total_gen) {
//                    return $users_array;
//                }
//                // exit(print_r($user));
//                if (intval($user["up_user_id"]) > 0) {
//                    return  self::getParentRelations($user["up_user_id"],$father, $now_gen, $total_gen, $users_array);
//                }
//            } else {
//                $users_array[] = $user;
//                $now_gen++;
//                 echo $now_gen . PHP_EOL;
//                if ($now_gen > $total_gen) {
//                    return $users_array;
//                }
//                if (intval($user["up_user_id"]) > 0) {
//                    return  self::getParentRelations($user["up_user_id"],$father, $now_gen, $total_gen, $users_array);
//                }
//            }
            
            
        }
//        echo '没有上级'.$uid.'p='.$father.PHP_EOL;
        //没有上级直接返回
        return $users_array;
    }
    /**
     * 获取父级用户
     */
    public static function getParent($pid)
    {
        $user = db("user")->where("id", $pid)->find();
        return $user ?? [];
    }

    /**
     * 获取限制的点位数量
     */
    private static function getLimitPositionNum($expert_level)
    {

        //达人级别的点位数量
        $level_type = 1;
        $limit_position_num = 3;

        return ["level_type" => $level_type, "limit_position_num" => $limit_position_num];
    }


    /**
     * 自己作为树形顶级,插入自己的关系和占位
     */
    public static function insertTopPositionAndRelation($user_id, $expert_level, $admin_id)
    {
        $level_info = self::getLimitPositionNum($expert_level);
        $level_type = $level_info["level_type"];
        $limit_position_num = $level_info["limit_position_num"];

        //插入占位
        db("expert_position")->insert([
            "user_id" => $user_id,
            "level_type" => $level_type,
            "limit_position_num" => $limit_position_num,
            "addtime" => time(),
        ]);

        //插入关系记录
        db("expert_relation")->insert([
            "user_id" => $user_id,
            "up_user_id" => 0,
            "addtime" => time(),
        ]);

        //插入升级记录
        $history = [
            "is_system" => 1,
            "admin_id" => $admin_id,
            "user_id" => $user_id,
            "before_level" => 0,
            "after_level" => $expert_level,
            "note" => "后台设置升级",
            "addtime" => time()
        ];
        db("expert_upgrade_history")->insert($history);
    }


    /**
     * 后台改变了达人或市场级别
     * @param int $uid 
     * @param int $expert_level  达人级别
     */
    public static function changeLevel($uid, $expert_level)
    {
        //查找点位配置信息
        $level_info = self::getLimitPositionNum($expert_level);
        $level_type = $level_info["level_type"];
        $limit_position_num = $level_info["limit_position_num"];

        //存在占位,更新占位数量
        $expert_position = db("expert_position")->where("user_id", $uid)->find();
        // exit(print_r($user));
        if ($expert_position) {
            db("expert_position")->where("user_id", $uid)->update(["level_type" => $level_type, "limit_position_num" => $limit_position_num, "addtime" => time()]);

            return false;
        }
    }


    /**
     * 升级为达人
     * @param int $uid 
     * @param int $expert_level  达人级别
     */
    public static function upgradeExpert($uid, $expert_level)
    {
        //用户是否存在
        $user = db("user")->where("id", $uid)->find();
        // exit(print_r($user));
        if (!$user) {
            throw new Exception("没有用户：" . $uid);
        }

        //查找点位配置信息
        $level_info = self::getLimitPositionNum($expert_level);
        $level_type = $level_info["level_type"];
        $limit_position_num = $level_info["limit_position_num"];

        //存在占位,更新占位数量
        $expert_position = db("expert_position")->where("user_id", $uid)->find();
        // exit(print_r($user));
        if ($expert_position) {
            db("expert_position")->where("user_id", $uid)->update(["level_type" => $level_type, "limit_position_num" => $limit_position_num, "addtime" => time()]);
//            throw new Exception("用户：" . $uid . " 已存在占位，只更新占位数量");
            return TRUE;
        }

        //存在关系
        $expert_relation = db("expert_relation")->where("user_id", $uid)->find();
        // exit(print_r($user));
        if ($expert_relation) {
//            throw new Exception("用户：" . $uid . " 已存在关系");
             return TRUE;
        }

        //当前用户还没有升级过，先查找直接推荐人
        $parent_user = db("user")->where("id",  $user["parent_user_id"])->find();
        // exit(print_r($parent_user));
        if (!$parent_user) {
            throw new Exception("用户" . $uid . " 不存在直接推荐人");
        }

        //如果推荐人不是达人，直接返回
        if ($parent_user["expert_level"] <= 0) {
            throw new Exception("用户" . $uid . " 推荐人不是达人");
        }

        $user_ids = [];
        $user_ids[] = $parent_user["id"];
        // exit(print_r($user_ids));

        $result = self::findPosition($user_ids, 1);
        //         exit(print_r($result));

        //为当前用户找到空的位置
        if ($result && $result["position"]) {

            try {
                db()->startTrans();

                $found_position = $result["position"];
                $p = $result["p"];

                $updaData= [$p => $user["id"]];
                if(!empty($result["is_sliped"])){
                   $updaData["is_sliped"] = $result["is_sliped"];
                }
                //更新找到的位置
                db("expert_position")->where("id", $found_position["id"])->update($updaData);

                //插入自己的占位记录
                $my_position = [
                    "user_id" => $user["id"],
                    "level_type" => $level_type,
                    "limit_position_num" => $limit_position_num,
                    "addtime" => time(),
                ];
                db("expert_position")->insert($my_position);

                //插入级别关系
                $my_relation = [
                    "user_id" => $user["id"],
                    "up_user_id" => $found_position["user_id"],
                    "addtime" => time(),
                    "status" => 1,
                ];
                db("expert_relation")->insert($my_relation);

                db()->commit();

                return true;
            } catch (Exception $e) {

                db()->rollback();
                Log::write($e->getMessage() . "\r\n" . $e->getFile() . "=" . $e->getLine());
                return false;
            }
        } else {
            throw new Exception("用户" . $uid . "  找不到占位");
        }
        return false;
    }

    /**
     * 查找空位置
     * $directly 是否直属 0 否 ；1是
     * $now_round 是否滑落 0 否 ；1是
     */
    public static function findPosition($user_ids, $directly = 1, $is_sliped = 0, $now_round = 1, $round = 100)
    {
        if (!$user_ids) {
            return ["position" => null, "p" => ""];
        }

        //超出查找的最大层次
        if ($now_round > $round) {
            return ["position" => null, "p" => ""];
        }

        $new_search_user_ids = [];
        foreach ($user_ids as $user_id) {

            $expert_position = db("expert_position")->where("user_id", $user_id)->find();
            if ($expert_position) {
                //记录子所有节点
                for ($i = 1; $i <= $expert_position['limit_position_num']; $i++) {
                    if ($expert_position["p{$i}"] != 0) {
                        $new_search_user_ids[] = $expert_position["p{$i}"];
                    }
                }



                if ($expert_position['is_sliped'] == 1 && $directly == 0) { //已经分配滑落 并且不是直推跳过
                    continue;
                }
                $expert_position['limit_position_num'] = $expert_position['limit_position_num'] > 8 ? 8 : $expert_position['limit_position_num'];
                for ($i = 1; $i <= $expert_position['limit_position_num']; $i++) {
                    if ($expert_position["p{$i}"] == 0) {
                        return ["position" => $expert_position, "p" => "p{$i}", 'is_sliped' => $is_sliped];
                    }
                }
            } else {
                //可能断层了
                //                return ["position" => null, "p" => ''];
                Log::write("查找点位出现断层 user_id".$user_id);
                continue;
            }

            //            $new_search_user_ids =  [$expert_position["p1"], $expert_position["p2"], $expert_position["p3"], $expert_position["p4"], $expert_position["p5"], $expert_position["p6"], $expert_position["p7"], $expert_position["p8"]];
            //            $new_search_user_ids = [];//


            //            $new_search_user_ids = array_filter($new_search_user_ids);
        }
        //        var_dump($new_search_user_ids);
        //查找下一级的所有节点
        if ($new_search_user_ids) {
            $now_round++;
            //滑落
            return self::findPosition($new_search_user_ids, 0, 1, $now_round, $round);
        }
    }
}
